"use strict";
const Package = require("@yk-cli-dev/package");
const log = require("@yk-cli-dev/log");
const path = require("path");
const chidProcess = require("child_process");
const { isObject } = require("@yk-cli-dev/utils");
const SETTINGS = {
  init: "@yk-cli-dev/utils",
};
const CATCH_DIR = "dependencies";
async function exec() {
  let storeDir = "";
  let pkg;
  let targetPath = process.env.CLI_TARGET_PATH;
  const homePath = process.env.CLI_HOME_PATH;
  const cmdObj = arguments[arguments.length - 1];
  const cmdName = cmdObj.name();
  const packageName = SETTINGS[cmdName];
  console.log(cmdName,'cmdObj',packageName);
  const packageVersion = "latest";
  if (process.env.LOG_LEVEL == "verbose" && targetPath) {
    log.info("targetPath", targetPath);
    log.info("homePath", homePath);
  }
  if(!targetPath) {
    targetPath = path.resolve(__dirname, '../../init/lib')  
    // targetPath = path.resolve(__dirname, '../../../commands/init/lib') 
    // targetPath = path.resolve(__dirname, '../init')  
    // targetPath ='../init';
  }
  // if(!storeDir){
  //   storeDir = path.resolve(targetPath, "node_modules");
  // }
  if (!targetPath) {
    //目标路径如果不存在就生成缓存路径
    targetPath = path.resolve(__dirname, '../../init/lib');
    // targetPath = path.resolve(__dirname, '../../../commands/init/lib') 
    // targetPath = path.resolve(__dirname, '../init');
    console.log(__dirname,targetPath,'__dirname');
    // targetPath = '../init';
    storeDir = path.resolve(targetPath, "node_modules");
    if (process.env.LOG_LEVEL == "verbose") {
      log.info("targetPath", targetPath);
      log.info("storeDir", storeDir);
      log.info("homePath", homePath);
    }
    pkg = new Package({
      targetPath,
      packageName,
      packageVersion,
      storeDir,
    });
    if (await pkg.exists()) {
      //更新package
      await pkg.update();
    } else {
      // 安装package
      await pkg.install();
    }
  } else {
    pkg = new Package({
      targetPath,
      packageName,
      packageVersion,
      storeDir,
    });
  }
  const rootFile = pkg.getRootFilePath(); //获取文件的入口路径
  console.log(rootFile, "rootFile===>sssss");
  if (rootFile) {
    // console.log(rootFile, "rootFile===>");

    try {
      //当前进程调用
      // require(path.resolve(rootFile)).call(null, Array.from(arguments));
      //在子进程中调用
      const args = Array.from(arguments);

      const cmd = args[args.length - 1];
      // console.log(args,cmd,"args===>");
      const o = Object.create(null);
      Object.keys(cmd).forEach((k) => {
        if (cmd.hasOwnProperty(k) && k.startsWith("_") && k !== "parent") {
          o[k] = cmd[k];
        }
        if (k == "commands") {
          o[k] = { ...cmd[k], parent: null };
        }
      });
      args.forEach((k) => {
        if (isObject(k)) {
          k.parent = null;
        }
      });
      console.log(cmd,'cmd1');
      args[args.length - 1] = o;
      const code = `require(path.resolve('${rootFile}')).call(null,${JSON.stringify(
        args
      )})`;
      // const code = `require("@yk-cli-dev/init").call(null,${JSON.stringify(
      //   args
      // )})`;
      const child = spawn("node", ["-e", code], {
        cwd: process.cwd(),
        stdio: "inherit",
      });
      console.log(cmd,'cmd2',code);
      child.on("error", (err) => {
        log.error(err);
      });
      child.on("exit", (e) => {
        console.log(e, "===命令执行成功");
      });
    } catch (error) {
      log.error(error);
    }
  }
}
function spawn(command, args, options) {
  const win32 = process.platform === "win32";
  const cmd = win32 ? "cmd" : command;
  const commandArgs = win32 ? ["/c"].concat(command, args) : args;
  return chidProcess.spawn(cmd, commandArgs, options || {});
}

module.exports = exec;
